// static/users/js/student-form.js
// 等待DOM完全加载
document.addEventListener('DOMContentLoaded', function() {
    // 1. 初始化表单元素
    const studentForm = document.getElementById('studentForm');
    const submitBtn = document.getElementById('submitBtn');
    const hasEnglish = document.getElementById('id_has_english');
    const englishType = document.getElementById('id_english_type');
    const hasMath = document.getElementById('id_has_math');
    const mathType = document.getElementById('id_math_type');

    // 2. 表单提交逻辑 (AJAX)
    if (studentForm && submitBtn) {
        studentForm.addEventListener('submit', function(e) {
            e.preventDefault(); // 阻止默认表单提交

            // 核心新增：处理禁用字段传值问题
            if (hasEnglish && englishType && !hasEnglish.checked) {
                englishType.disabled = false;
                englishType.value = '不考';
            }
            if (hasMath && mathType && !hasMath.checked) {
                mathType.disabled = false;
                mathType.value = '不考';
            }

            const formData = new FormData(this);
            const originalBtnText = submitBtn.innerHTML;

            // 【核心修复】明确指定表单提交URL，避免使用 this.action
            let formAction;
            if (this.action && this.action !== '' && !this.action.includes('{%')) {
                formAction = this.action;
            } else {
                formAction = window.location.pathname;
            }

            // 显示加载状态
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>保存中...';

            // 发送AJAX请求
            fetch(formAction, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                }
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(err => { throw err; });
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    // 提交成功
                    showAlert('success', data.message);

                    // 【修复】重定向逻辑：优先使用后端返回的 redirect_url
                    if (data.redirect_url) {
                        setTimeout(() => {
                            window.location.href = data.redirect_url;
                        }, 1500);
                    } else {
                        // 【新增】根据当前页面决定重定向目标
                        const currentPath = window.location.pathname;

                        if (currentPath.includes('/create/')) {
                            // 创建模式：重定向到学生列表
                            setTimeout(() => {
                                window.location.href = '/users/';
                            }, 1500);
                        } else if (currentPath.includes('/edit/')) {
                            // 编辑模式：重定向到当前学生的详情页
                            // 从URL中提取学生ID：/users/{student_id}/edit/
                            const pathParts = currentPath.split('/');
                            const studentId = pathParts[2]; // 获取学生ID
                            setTimeout(() => {
                                window.location.href = `/users/${studentId}/detail/`;
                            }, 1500);
                        } else {
                            // 默认重定向到学生列表
                            setTimeout(() => {
                                window.location.href = '/users/';
                            }, 1500);
                        }
                    }
                } else {
                    // 提交失败，显示表单错误
                    if (data.errors) {
                        showFormErrors(data.errors);
                    } else {
                        showAlert('danger', '保存失败，请检查表单数据。');
                    }
                }
            })
            .catch(error => {
                console.error('表单提交失败:', error);
                showAlert('danger', '网络异常或服务器错误，保存失败，请稍后重试。');
            })
            .finally(() => {
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalBtnText;
                if (hasEnglish && englishType) {
                    englishType.disabled = !hasEnglish.checked;
                }
                if (hasMath && mathType) {
                    mathType.disabled = !hasMath.checked;
                }
            });
        });
    }

    // 3. 科目选择联动逻辑
    function toggleSubjectField() {
        if (hasEnglish && englishType) {
            englishType.disabled = !hasEnglish.checked;
            if (!hasEnglish.checked) {
                englishType.selectedIndex = 0;
            }
        }
        if (hasMath && mathType) {
            mathType.disabled = !hasMath.checked;
            if (!hasMath.checked) {
                mathType.selectedIndex = 0;
            }
        }
    }
    toggleSubjectField();
    if (hasEnglish) hasEnglish.addEventListener('change', toggleSubjectField);
    if (hasMath) hasMath.addEventListener('change', toggleSubjectField);

    // 4. 显示表单字段错误信息
    function showFormErrors(errors) {
        clearFormErrors();
        for (const fieldName in errors) {
            if (fieldName === '__all__') {
                errors[fieldName].forEach(errorMsg => {
                    showAlert('danger', errorMsg);
                });
                continue;
            }
            const fieldElement = document.getElementById(`id_${fieldName}`);
            if (fieldElement) {
                fieldElement.classList.add('is-invalid');
                const errorDiv = document.createElement('div');
                errorDiv.className = 'invalid-feedback';
                errorDiv.innerHTML = errors[fieldName].join('<br>');
                fieldElement.parentNode.insertBefore(errorDiv, fieldElement.nextSibling);
                fieldElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
                fieldElement.focus();
            }
        }
    }

    // 5. 清除所有表单错误
    function clearFormErrors() {
        document.querySelectorAll('.is-invalid').forEach(el => {
            el.classList.remove('is-invalid');
        });
        document.querySelectorAll('.invalid-feedback').forEach(el => {
            el.remove();
        });
    }

    // 6. 显示顶部提示框
    function showAlert(alertType, message) {
        const existingAlert = document.querySelector('.alert');
        if (existingAlert) {
            const bootstrapAlert = bootstrap.Alert.getInstance(existingAlert);
            bootstrapAlert.close();
        }

        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${alertType} alert-dismissible fade show`;
        alertDiv.role = 'alert';
        alertDiv.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        `;

        const formCard = document.querySelector('.student-form-card');
        if (formCard) {
            formCard.parentNode.insertBefore(alertDiv, formCard);
        } else {
            const container = document.querySelector('.student-form-container');
            if (container) {
                container.prepend(alertDiv);
            } else {
                document.body.prepend(alertDiv);
            }
        }

        setTimeout(() => {
            const bootstrapAlert = bootstrap.Alert.getOrCreateInstance(alertDiv);
            bootstrapAlert.close();
        }, 5000);

        alertDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }

    // 7. 重置按钮逻辑增强
    const resetBtn = document.querySelector('button[type="reset"]');
    if (resetBtn) {
        resetBtn.addEventListener('click', function() {
            clearFormErrors();
            setTimeout(toggleSubjectField, 100);
        });
    }

    // 8. 输入框聚焦时清除单个错误
    const formInputs = document.querySelectorAll('.student-form-input, .student-form-select, .student-form-textarea');
    formInputs.forEach(input => {
        input.addEventListener('focus', function() {
            if (this.classList.contains('is-invalid')) {
                this.classList.remove('is-invalid');
                const errorElement = this.nextElementSibling;
                if (errorElement && errorElement.classList.contains('invalid-feedback')) {
                    errorElement.remove();
                }
            }
        });
    });
});